//
// Created by yexf_ on 2024/8/13.
//

#ifndef SIGNAL_CALC_STRING_CONVERT_H
#define SIGNAL_CALC_STRING_CONVERT_H
#pragma once

#include <list>
#include <codecvt>
#include <vector>
#include <locale>
#include <iostream>
#include <optional>
#include "base/win32/platform_string_util.h"

inline std::string UnicodeToUtf8(const std::wstring &wstr) {

    std::string out;
    try {

        std::wstring_convert<std::codecvt_utf8<wchar_t>> wcv;
        out = wcv.to_bytes(wstr);
    }
    catch (const std::exception &e) {

        std::cerr << e.what() << std::endl;
    }
    return out;
}

inline std::wstring Utf8ToUnicode(const std::string &str) {

    std::wstring ret;
    try {

        std::wstring_convert<std::codecvt_utf8<wchar_t>> wcv;
        ret = wcv.from_bytes(str);
    }
    catch (const std::exception &e) {

        std::cerr << e.what() << std::endl;
    }
    return ret;
}

inline std::string UnicodeToAnsi(const std::wstring &wstr) {
    std::string ret;
    if (obase::win32::UnicodeToMBCS(wstr, ret)) return ret;
    return "";
}

inline std::wstring AnsiToUnicode(const std::string &str) {
    std::wstring ret;
    if (obase::win32::MBCSToUnicode(str, ret)) return ret;
    return L"";
}

inline std::optional<std::vector<std::wstring>> split(const std::wstring& input, const std::wstring& delimitor)
{
    std::vector<std::wstring> output;
    std::wstring input2(input);

    if (input2.empty())
        return output;

    wchar_t *token = wcstok(&input2[0], delimitor.c_str());
    while (token != NULL)
    {
        output.push_back(token);
        token = wcstok(NULL, delimitor.c_str());
    }
    return output;
}

inline std::optional<std::vector<std::string>> split(const std::string& input, const std::string& delimitor)
{
    std::vector<std::string> output;
    std::string input2(input);

    if (input2.empty())
        return output;

    char *token = strtok(&input2[0], delimitor.c_str());
    while (token != NULL)
    {
        output.push_back(token);
        token = strtok(NULL, delimitor.c_str());
    }
    return output;
}

#endif //SIGNAL_CALC_STRING_CONVERT_H
